//
//  YHTabBar.swift
//  SniaWeiBo
//
//  Created by lcc on 16/5/11.
//  Copyright © 2016年 lcc. All rights reserved.
//

import UIKit

class YHTabBar: UITabBar {

    //设置闭包
    var composeButtonClousre: (()->())?
    
    //使用懒加载创建撰写按钮
    private lazy var composerButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "clickAddBtn", forControlEvents: .TouchUpInside)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState:.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState:.Highlighted)
        button.sizeToFit()
        
        return button
    
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    private func setUpUI() {
    
        addSubview(composerButton)
    }
    
    //加载xib，storyBoard时调用
    required init?(coder aDecoder: NSCoder) {

        //支持xib的写法
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    //设置加号按钮的位置
    override func layoutSubviews() {
        
        composerButton.center.x = frame.size.width * 0.5
        composerButton.center.y = frame.size.height * 0.5
        
        //计算子视图按钮大小
        let itemW = frame.size.width / 5
        var index = 0
        for childView in subviews {
        
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                childView.frame.size.width = itemW
                childView.frame.origin.x = itemW * CGFloat(index)
                index++
                
                //处理加号按钮位置
                if index == 2 {
                    index++
                }
            }
        }
    }
      @objc private func clickAddBtn() {
        
        print("点击了中间加号按钮")
        
        composeButtonClousre?()
    }
    
}
